package net.dgg.zz.credential.warningConfigure.service;

import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.iboss.base.service.CmsService;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.zz.common.base.service.BaseService;
import net.dgg.zz.common.constant.CredentialConstant;
import net.dgg.zz.common.service.CommonService;
import net.dgg.zz.common.systemRecord.entity.SystemRecord;
import net.dgg.zz.common.systemRecord.service.SystemRecordService;
import net.dgg.zz.common.utils.StringUtils;
import net.dgg.zz.common.utils.ValidateUtils;
import net.dgg.zz.credential.excption.CertificateExcption;
import net.dgg.zz.credential.generalCredential.service.GeneralCredentialService;
import net.dgg.zz.credential.warningConfigure.constant.WarningType;
import net.dgg.zz.credential.warningConfigure.dao.WarningConfigureDao;
import net.dgg.zz.credential.warningConfigure.dto.WarningConfigureDto;
import net.dgg.zz.credential.warningConfigure.entity.WarningConfigure;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zsx
 * @Title: CertificateConfigureService
 * @ProjectName zzsc
 * @Description: 证书系统配置
 * @date 2018/8/13 15:42
 */
@Service
public class SystemConfigureService extends BaseService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WarningConfigureDao warningConfigureDao;
    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private CmsService cmsService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private SystemRecordService systemRecordService;
    @Autowired
    private GeneralCredentialService generalCredentialService;
    @Autowired
    private SystemConfigureService systemConfigureService;

    /*
     * @Author zsx
     * @Date 2018-08-13 04:08:53
     * @Description
     * @param params
     * @return List<WarningConfigure>
     */
    public List<WarningConfigure> queryWarningConfigByWithPage(Map<String, Object> params) {
        if (params.containsKey("isAll") && params.get("isAll").equals("0")) {
            params.put("signOrgId", commonService.findUserSyb(sessionManager.getCurrentUser()));
        }
        if (null == params.get("orderColumn")) {
            params.put("orderDir", "desc");//排序方向
            params.put("orderColumn", "create_time");//排序的列
        }
        return warningConfigureDao.selectWarningConfigByWithPage(params);
    }


    /*
     * @Author zsx
     * @Date 2018-08-14 09:08:16
     * @Description 添加预警配置
     * @param configure
     * @return void
     */
    @Transactional
    public String addWarningConfig(Long signOrgId, String warningType, String signOrgName) {
        UserEntity user = this.sessionManager.getCurrentUser();
        if (null == user) {
            logger.info("未获取到当前登录人未获取到当前登录人");
            return "未获取到当前登录人";
        }
        WarningConfigure configure = warningConfigureDao.selectBySignOrgIdAndWarningType(signOrgId, warningType);
        if (null != configure) {
            logger.info("{}已经存在系统配置了，不能重复新增");
            return "该事业部已经存在配置，不能重复添加";
        }
        configure = new WarningConfigure();
        Long defaultData = 0L;
        configure.setId(DggKeyWorker.nextId());
        configure.setSignOrgId(signOrgId);
        configure.setSignOrgName(signOrgName);
        configure.setCapitalPoolWarning(BigDecimal.ZERO);
        configure.setStorageWarning(defaultData);
        configure.setCertificateHangUpWarning(defaultData);
        configure.setCertificateExpireWarning(defaultData);
        configure.setCertificateNotUsedWarning(defaultData);
        configure.setTalentContractWarning(defaultData);
        configure.setCompanyContractWarning(defaultData);
        configure.setReviewProgression(2);//默认2级
        configure.setWarningType(warningType);
        configure.setStatus(CredentialConstant.EFFECTIVE_CONFIGURE_STATUS);
        this.saveOpt(configure, user);
        warningConfigureDao.insertSelective(configure);
        //日志
        SystemRecord record = new SystemRecord();
        String remark = "";
        if (warningType.equals(CredentialConstant.GENERAL_CREDENTIAL)) {
            record.setSource("1");
            remark = signOrgName + "添加了证书管理系统配置";
        } else {
            record.setSource("4");
            remark = signOrgName + "添加了资质管理系统配置";
        }
        record.setOperateType("1");
        record.setWorkId(configure.getId());
        record.setWorkTableName("zz_warning_configure");
        record.setRemarks(remark);
        systemRecordService.save(record);
        return "";
    }

    /*
     * @Author zsx
     * @Date 2018-08-14 11:08:03
     * @Description 更新系统配置
     * @param configure
     * @return void
     */
    @Transactional
    public Map<String, Object> updateWarningConfig(WarningConfigureDto configureDto) {
        Map<String, Object> map = new HashMap<>();
        map.put("status", true);
        UserEntity user = this.sessionManager.getCurrentUser();
        if (null == user) {
            map.put("status", false);
            map.put("msg", "未获取到当前登录人");
        }
        WarningConfigure configure = new WarningConfigure();
        this.updateOpt(configure, user);
        copyWarningConfig(configure, configureDto);
        warningConfigureDao.updateByPrimaryKeySelective(configure);

        //日志
        SystemRecord record = new SystemRecord();
        String remark = "";
        String workTableName = "";
        if (configureDto.getWarningType().equals(CredentialConstant.GENERAL_CREDENTIAL)) {
            record.setSource("1");
            remark = "修改证书管理系统配置";
            workTableName = "zz_warning_configure,zz_capital_pool_count";
        } else {
            record.setSource("4");
            remark = "修改资质管理系统配置";
            workTableName = "zz_warning_configure";
        }
        record.setWorkId(configureDto.getId());
        record.setOperateType("2");
        record.setWorkTableName(workTableName);
        record.setRemarks(remark);
        systemRecordService.save(record);
        return map;
    }


    /*
     * @Author zsx
     * @Date 2018-08-16 03:08:23
     * @Description  根据事业部更新单个预警值
     * @param Map<String, Object>
     *     warningType 证书资质类型
     *     warningName  参考WarningType 传code
     *     warningValue 预警值
     * @return Map<String, Object>
     */
    @Transactional
    public Map<String, Object> updateSingleWarning(Map<String, Object> params) {
        ValidateUtils.strNotEmpty(params.get("signOrgId"), CertificateExcption.class, "事业部id不能为空");
        ValidateUtils.strNotEmpty(params.get("warningType"), CertificateExcption.class, "预警类型不能为空");
        ValidateUtils.strNotEmpty(params.get("warningName"), CertificateExcption.class, "预警名称不能为空");
        ValidateUtils.strNotEmpty(params.get("warningValue"), CertificateExcption.class, "预警值不能为空");
        Map<String, Object> map = new HashMap<>();
        map.put("status", true);
        UserEntity user = this.sessionManager.getCurrentUser();
        if (null == user) {
            map.put("status", false);
            map.put("msg", "未获取到当前登录人");
        }
        Long signOrgId = Long.valueOf(params.get("signOrgId").toString());
        String warningType = params.get("warningType").toString();
        WarningConfigure configure = warningConfigureDao.selectBySignOrgIdAndWarningType(signOrgId, warningType);
        if (null == configure) {
            //根据事业部id获取事业部名称
            Map org = cmsService.findOrg(signOrgId);
            String signOrgName = org.get("name").toString();
            addWarningConfig(signOrgId, warningType, signOrgName);
        }
        String warningName = (String) params.get("warningName");
        String fieldName = WarningType.getNameByFieldName(warningName);
        params.put("fieldName", fieldName);
        params.put("updaterId", user.getId());
        params.put("updaterName", user.getRealName() + user.getLoginName());
        params.put("updateTime", new Date());
        params.put("updaterOrgId", user.getOrgId());
        warningConfigureDao.updateBySignOrgIdAndWarningType(params);
        //日志
        SystemRecord record = new SystemRecord();
        record.setSource("1");
        record.setOperateType("2");
        record.setWorkTableName("zz_warning_configure");
        record.setRemarks("修改单个预警值:事业部" + signOrgId + "修改字段" + fieldName);
        systemRecordService.save(record);
        return map;
    }

    /*
     * @Author zsx
     * @Date 2018-08-17 09:08:09
     * @Description 根据事业部id，类型，配置名称查询配置值
     * @param params
     * @return Map<String, Object>
     */
    public Map<String, Object> querySingleWarning(Map<String, Object> params) {
        Map<String, Object> map = new HashMap<>();
        map.put("status", true);
        if (null == params.get("signOrgId")) {
            map.put("status", false);
            map.put("msg", "事业部ID不能为空");
            return map;
        }
        if (null == params.get("warningType")) {
            map.put("status", false);
            map.put("msg", "类型不能为空");
            return map;
        }
        if (null == params.get("warningName")) {
            map.put("status", false);
            map.put("msg", "预警名称不能为空");
            return map;
        }
        String warningName = params.get("warningName").toString();
        String fieldName = WarningType.getNameByFieldName(warningName);
        params.put("fieldName", fieldName);
        Long configValue = warningConfigureDao.querySingleWarning(params);
        map.put("configValue", configValue);
        return map;
    }

    /*
     * @Author zsx
     * @Date 2018-08-16 02:08:06
     * @Description  将configureDto 的值复制给configure
     * @return void
     */
    private void copyWarningConfig(WarningConfigure configure, WarningConfigureDto configDto) {
        configure.setId(configDto.getId());
        configure.setCapitalPoolWarning(configDto.getCapitalPoolWarning() == null ? BigDecimal.ZERO : configDto.getCapitalPoolWarning());
        configure.setStorageWarning(configDto.getStorageWarning() == null ? 0 : configDto.getStorageWarning());
        configure.setCertificateExpireWarning(configDto.getCertificateExpireWarning() == null ? 0 : configDto.getCertificateExpireWarning());
        configure.setCertificateNotUsedWarning(configDto.getCertificateNotUsedWarning() == null ? 0 : configDto.getCertificateNotUsedWarning());
        configure.setCertificateHangUpWarning(configDto.getCertificateHangUpWarning() == null ? 0 : configDto.getCertificateHangUpWarning());
        configure.setCompanyContractWarning(configDto.getCompanyContractWarning() == null ? 0 : configDto.getCompanyContractWarning());
        configure.setTalentContractWarning(configDto.getTalentContractWarning() == null ? 0 : configDto.getTalentContractWarning());
        configure.setReviewProgression(configDto.getReviewProgression() == null ? 0 : configDto.getReviewProgression());
    }


    /**
     * 根据事业部id查询事业部设置的库容预警值
     *
     * @param orgId
     * @param generalCredential
     * @return
     */
    public WarningConfigure findConfigureByOrgId(Long orgId, String generalCredential) {
        if (null == orgId) {
            UserEntity user = sessionManager.getCurrentUser();
            orgId = commonService.findUserSyb(user);
        }
        return warningConfigureDao.selectBySignOrgIdAndWarningType(orgId, generalCredential);
    }

    /**
     * 证书总览：资金池预警
     *
     * @param params
     * @return
     */
    public List<Map> warningConfigure(Map params) {
        if (params.containsKey("isAll") && params.get("isAll").equals("0")) {
            params.put("signOrgId", commonService.findUserSyb(sessionManager.getCurrentUser()));
        }
        params.put("generalType", CredentialConstant.GENERAL_CREDENTIAL);
        return warningConfigureDao.warningConfigure(params);
    }

    /**
     * 验证资金池额度
     *
     * @param signOrgId
     */
    public Boolean checkCaptialPool(Long signOrgId) {
        Map params = new HashMap();
        params.put("signOrgId", signOrgId);
        params.put("generalType", CredentialConstant.GENERAL_CREDENTIAL);
        WarningConfigure warningConfigure = warningConfigureDao.selectBySignOrgIdAndWarningType(signOrgId, CredentialConstant.GENERAL_CREDENTIAL);
        if (StringUtils.isEmpty(warningConfigure)) {
            return true;
        }
        List<Map> count = systemConfigureService.warningConfigure(params);
        if (StringUtils.isEmpty(count) || count.size() < 1) {
            //资金池金额大于0
            if (new BigDecimal("0").compareTo(warningConfigure.getCapitalPoolWarning()) < 0) {
                return true;
            }
        } else {
            // 计算事业部资金池金额
            if (count.size() == 1) {
                Map map = count.get(0);
                // 现有资金池额度大于0
                if (new BigDecimal(map.get("nowCapitalPoolWarning").toString()).compareTo(new BigDecimal("0")) > 0) {
                    return true;
                }
            }
        }
        return false;
    }
}
